<template>
  <view class="bind-info-page">
    <!-- 身份证信息 -->
    <view class="card">
      <view class="card-title">
        <text class="title-text">身份证信息</text>
      </view>
      
      <view class="upload-section">
        <!-- 身份证正面 -->
        <view class="upload-item">
          <view class="upload-box" @click="uploadIdCard('front')">
            <image v-if="idCardFront" :src="idCardFront" class="uploaded-image" mode="aspectFit"></image>
            <view v-else class="upload-placeholder">
              <image class="upload-icon" src="/static/static/images/more.png"></image>
              <text class="upload-text">上传身份证正面</text>
            </view>
          </view>
        </view>
        
        <!-- 身份证反面 -->
        <view class="upload-item">
          <view class="upload-box" @click="uploadIdCard('back')">
            <image v-if="idCardBack" :src="idCardBack" class="uploaded-image" mode="aspectFit"></image>
            <view v-else class="upload-placeholder">
              <image class="upload-icon" src="/static/static/images/more.png"></image>
              <text class="upload-text">上传身份证反面</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 身份证信息展示 -->
      <view class="info-display" v-if="idCardInfo.name">
        <view class="info-row">
          <text class="info-label">姓名：</text>
          <text class="info-value">{{ idCardInfo.name }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">身份证号：</text>
          <text class="info-value">{{ idCardInfo.idNumber }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">有效期：</text>
          <text class="info-value">{{ idCardInfo.validStart }} -- {{ idCardInfo.validEnd }}</text>
        </view>
      </view>
    </view>
    
    <!-- 银行卡信息 -->
    <view class="card">
      <view class="card-title">
        <text class="title-text">银行卡信息</text>
      </view>
      
      <!-- 银行卡上传 -->
      <view class="upload-item">
        <view class="upload-box" @click="uploadBankCard">
          <image v-if="bankCardFront" :src="bankCardFront" class="uploaded-image" mode="aspectFit"></image>
          <view v-else class="upload-placeholder">
            <image class="upload-icon" src="/static/static/images/more.png"></image>
            <text class="upload-text">上传银行卡正面</text>
          </view>
        </view>
      </view>
      
      <!-- 银行卡信息展示 -->
      <view class="info-display" v-if="bankCardInfo.cardNumber">
        <view class="info-row">
          <text class="info-label">银行卡号：</text>
          <text class="info-value">{{ bankCardInfo.cardNumber }}</text>
        </view>
      </view>
      
      <!-- 银行卡绑定手机号 -->
      <view class="form-item">
        <text class="form-label">银行卡绑定手机号</text>
        <input class="form-input" type="number" v-model="bankPhone" placeholder="请输入银行卡绑定的手机号" />
      </view>
      
      <!-- 银行所在地 -->
      <view class="form-item">
          <text class="form-label">银行所在地</text>
          <view class="location-select">
            <picker class="select-box" mode="selector" :range="provinceNames" @change="provinceChange">
              <view class="select-value">{{ provinceName || '请选择省份' }}</view>
            </picker>
            <picker class="select-box" mode="selector" :range="cityNames" @change="cityChange">
              <view class="select-value">{{ cityName || '请选择城市' }}</view>
            </picker>
          </view>
        </view>
    </view>
    
    <!-- 提交按钮 -->
    <view class="submit-btn" @click="submitForm" :class="{disabled: !canSubmit}">
      <text>提交绑定</text>
    </view>
    
    <!-- 加载提示 -->
    <view class="loading-mask" v-if="isSubmitting">
      <view class="loading-content">
        <text class="loading-text">正在验证银行卡信息...</text>
      </view>
    </view>
  </view>
</template>

<script>
	import areaData from './city.json';
import {
		commonOcr,
	} from '@/network/api.js'
import {
		getUserinfo,
		profile,
		uploadingImage,
	} from '@/network/loginAndMy.js'
import {
		pathToBase64,
		base64ToPath
	} from 'image-tools'
export default {
  data() {
    return {
      // 身份证相关
      idCardFront: '',
      idCardBack: '',
      frontProgress: 0,
      backProgress: 0,
      idCardInfo: {
        name: '',
        idNumber: '',
        validStart: '',
        validEnd: ''
      },
      
      // 银行卡相关
      bankCardFront: '',
      bankProgress: 0,
      bankCardInfo: {
        cardNumber: ''
      },
      bankPhone: '',
      
// 银行所在地
      areaData: {},          // 完整的地区数据对象
      provinceNames: [],     // 省份名称列表
      cityNames: [],         // 城市名称列表
      provinceName: '',      // 选中的省份名称
      cityName: '',          // 选中的城市名称
      selectedProvinceCode: '', // 选中的省份编码
      selectedCityCode: '',     // 选中的城市编码
      
      // 提交状态
      isSubmitting: false
    }
  },
  mounted() {
      // 初始化地区数据
      this.initAreaData();
    },
  computed: {
    canSubmit() {
      return (
        this.idCardFront && 
        this.idCardBack && 
        this.bankCardFront && 
        this.idCardInfo.name && 
        this.idCardInfo.idNumber && 
        this.bankCardInfo.cardNumber && 
        this.bankPhone && 
        this.provinceName && 
        this.cityName
      )
    }
  },
  methods: {
	  
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    uploadingImage(image_url) {
    	uploadingImage({
    		file: image_url
    	}).then(res => {
    		if (res.code == 1) {
    			return res.data;
    		}
    	})
    },
    // 上传身份证
    uploadIdCard(side) {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          if (side === 'front') {
              pathToBase64(res.tempFilePaths[0])
              	.then(path => {
            		this.simulateUpload('front',path)
              	})
              	.catch(error => {
              		console.error(error)
              	})
          } else {
            pathToBase64(res.tempFilePaths[0])
            	.then(path => {
					this.simulateUpload('back',path)
            	})
            	.catch(error => {
            		console.error(error)
            	})
          }
        }
      })
    },
    
    // 上传银行卡
    uploadBankCard() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
		  pathToBase64(res.tempFilePaths[0])
		  	.then(path => {
				this.simulateUpload('bank',path)
		  	})
		  	.catch(error => {
		  		console.error(error)
		  	})
        }
      })
    },
    
    // 真实上传
    simulateUpload(type,image_url) {
		const baseUrl = "https://huijiank.com";
      uploadingImage({
      	file: image_url
      }).then(res => {
      	if (res.code == 1) {
			if(type == 'front')
      		{
				console.log('正面',this.idCardFront)
				this.idCardFront = baseUrl+res.data
				this.getFrontIdCardInfo()
			}else if(type == 'back')
			{
				console.log(this.idCardBack)
				this.idCardBack = baseUrl+res.data
				this.getBackIdCardInfo()
			}else{
				console.log(this.bankCardFront)
				this.bankCardFront = baseUrl+res.data
				this.getBankCardInfo()
			}
      	}
      })
    },
    
    // 获取身份证正面信息
    getFrontIdCardInfo() {
      // 这里是调用接口获取身份证信息
      commonOcr({ image: this.idCardFront,type:'id_card-face' }).then(res => {
        if (res.code === 1) {
          this.idCardInfo.name = res.data.name
          this.idCardInfo.idNumber = res.data.num
        }
      })
    },
    
    // 获取身份证反面信息
    getBackIdCardInfo() {
      commonOcr({ image: this.idCardBack,type:'id_card-back' }).then(res => {
        if (res.code === 1) {
          this.idCardInfo.validStart = res.data.start_date
          this.idCardInfo.validEnd = res.data.end_date
        }
      })
    },
    
    // 获取银行卡信息
    getBankCardInfo() {
      commonOcr({ image: this.bankCardFront,type:'bank' }).then(res => {
        if (res.code === 1) {
          this.bankCardInfo.cardNumber = res.data.card_num
        }
      })
      
    },
    
// 初始化地区数据
    initAreaData() {
      try {
        // 确保JSON正确加载
        if (areaData && typeof areaData === 'object') {
          this.areaData = areaData;
          
          // 提取所有省份名称
          this.provinceNames = Object.keys(areaData);
          
          console.log('地区数据加载成功，省份数量:', this.provinceNames.length);
        } else {
          console.error('地区JSON格式不正确');
          // 设置默认省份作为后备
          this.provinceNames = ['北京市', '上海市', '广东省'];
        }
      } catch (error) {
        console.error('加载地区数据失败:', error);
        // 设置默认省份作为后备
        this.provinceNames = ['北京市', '上海市', '广东省'];
      }
    },
    
    // 省份选择变化
    provinceChange(e) {
      const index = e.detail.value;
      if (index >= this.provinceNames.length) return;
      
      this.provinceName = this.provinceNames[index];
      
      // 重置城市选择
      this.cityName = '';
      this.selectedCityCode = '';
      this.cityNames = [];
      
      // 查找选中的省份数据
      const provinceData = this.areaData[this.provinceName];
      
      if (provinceData && provinceData.items) {
        // 提取省份编码
        this.selectedProvinceCode = provinceData.val || '';
        
        // 提取该省份下的城市名称
        const cityData = provinceData.items;
        this.cityNames = Object.keys(cityData);
        
        console.log(`省份 ${this.provinceName} 下的城市:`, this.cityNames);
      } else {
        console.warn(`找不到省份 ${this.provinceName} 的城市数据`);
        this.cityNames = [];
      }
    },
    
    // 城市选择变化
    cityChange(e) {
      const index = e.detail.value;
      if (index >= this.cityNames.length) return;
      
      this.cityName = this.cityNames[index];
      
      // 获取省份数据
      const provinceData = this.areaData[this.provinceName];
      if (!provinceData || !provinceData.items) return;
      
      // 获取城市数据
      const cityData = provinceData.items[this.cityName];
      if (cityData) {
        // 提取城市编码
        this.selectedCityCode = cityData.val || '';
        
        // 如果需要区域信息，可以在这里处理
        if (cityData.items) {
          // 这里可以提取区域信息，但当前需求只需要城市
          // const districtNames = Object.keys(cityData.items);
        }
      }
    },
    
    
    
    // 提交表单
    submitForm() {
// 检查是否可以提交（添加省市区检查）
      if (!this.canSubmit) return;
      
      // 验证手机号格式
      if (!/^1[3-9]\d{9}$/.test(this.bankPhone)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none'
        });
        return;
      }
      
      // this.isSubmitting = true;
      
      // 准备提交数据（添加省市区）
      const formData = {
        name: this.idCardInfo.name,
        idNumber: this.idCardInfo.idNumber,
        cardNumber: this.bankCardInfo.cardNumber,
        bankPhone: this.bankPhone,
        province: this.provinceName,
        city: this.cityName,
        provinceCode: this.selectedProvinceCode,
        cityCode: this.selectedCityCode,
        frontImage: this.idCardFront,
        backImage: this.idCardBack,
        bankImage: this.bankCardFront,
        type: 'vehicle',
      };
      
      // 调用提交接口
      commonOcr(formData).then(res => {
        this.isSubmitting = false
        
        if (res.code === 1) {
          uni.showToast({
            title: '绑定成功',
            icon: 'success'
          })
          
          // 绑定成功后返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: res.msg || '银行卡验证失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        this.isSubmitting = false
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
      })
    }
  }
}
</script>

<style lang="scss">
.bind-info-page {
  padding: 20rpx 30rpx;
  background-color: #f5f7fa;
  min-height: 100vh;

  
  .card {
    background-color: #fff;
    border-radius: 24rpx;
    padding: 40rpx 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.05);
    
    .card-title {
      display: flex;
      align-items: center;
      font-size: 30rpx;
      font-weight: bold;
      margin-bottom: 40rpx;
      position: relative;
      padding-bottom: 20rpx;
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100rpx;
        height: 6rpx;
        background: linear-gradient(90deg, #B07412, #E3BA5B);
        border-radius: 3rpx;
      }
      
      
      .title-text {
        color: #333;
        font-weight: 600;
      }
    }
    
    .upload-section {
      display: flex;
      justify-content: space-between;
    }
    
    .upload-item {
      margin-bottom: 40rpx;
    }
    
    .upload-box {
      width: 320rpx;
      height: 220rpx;
      border: 2rpx dashed #e0e0e0;
      border-radius: 16rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #fafafa;
      transition: all 0.3s;
      
      &:active {
        background-color: #f5f5f5;
        transform: translateY(2rpx);
      }
      
      .uploaded-image {
        width: 100%;
        height: 100%;
        border-radius: 12rpx;
      }
      
      .upload-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .upload-icon {
          width: 64rpx;
          height: 64rpx;
          margin-bottom: 20rpx;
        }
        
        .upload-text {
          font-size: 26rpx;
          color: #999;
        }
      }
    }
    
    .upload-progress {
      height: 8rpx;
      background-color: #eee;
      border-radius: 4rpx;
      margin-top: 20rpx;
      overflow: hidden;
      
      .progress-bar {
        height: 100%;
        background: linear-gradient(90deg, #B07412, #E3BA5B);
        transition: width 0.3s;
      }
    }
    
    .info-display {
      background-color: #f9f9f9;
      border-radius: 16rpx;
      padding: 30rpx;
      margin-top: 30rpx;
      border-left: 4rpx solid #E3BA5B;
      
      .info-row {
        display: flex;
        margin-bottom: 20rpx;
        font-size: 30rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .info-label {
          color: #666;
          width: 180rpx;
          font-weight: 500;
        }
        
        .info-value {
          color: #333;
          font-weight: 600;
        }
      }
    }
    
    .form-item {
		margin: 21px 0px;
      
      .form-label {
        display: block;
        font-size: 30rpx;
        color: #333;
        margin-bottom: 20rpx;
        font-weight: 600;
      }
      
      .form-input {
        height: 90rpx;
        background-color: #f9f9f9;
        border-radius: 12rpx;
        padding: 0 30rpx;
        font-size: 26rpx;
        border: 1rpx solid #eee;
        transition: all 0.3s;
        
        &:focus {
          border-color: #E3BA5B;
          box-shadow: 0 0 0 2rpx rgba(227, 186, 91, 0.2);
        }
      }
      
      .location-select {
        display: flex;
        justify-content: space-between;
        gap: 20rpx;
        
        .select-box {
          flex: 1;
          height: 90rpx;
          background-color: #f9f9f9;
          border-radius: 12rpx;
          display: flex;
          align-items: center;
          padding: 0 30rpx;
          font-size: 26rpx;
          color: #333;
          border: 1rpx solid #eee;
          
          .select-value {
            color: #999;
          }
        }
      }
    }
  }
  
  .submit-btn {
    height: 88rpx;
    background: linear-gradient(90deg, #B07412, #E3BA5B);
    border-radius: 50rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-size: 36rpx;
    font-weight: bold;
    margin-top: 40rpx;
    box-shadow: 0 6rpx 20rpx rgba(176, 116, 18, 0.3);
    transition: all 0.3s;
    
    &:active {
      transform: translateY(4rpx);
      box-shadow: 0 4rpx 12rpx rgba(176, 116, 18, 0.3);
    }
    
    &.disabled {
      background: #ccc;
      box-shadow: none;
      opacity: 0.7;
    }
  }
  
  .loading-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;
    
    .loading-content {
      background-color: #fff;
      border-radius: 24rpx;
      padding: 30rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      min-width: 400rpx;
      
      .loading-text {
        font-size: 32rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
}
</style>